package com.my.cd.proxy.candymachine;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import com.my.cd.proxy.CandyMachineRemote;

/**
 * 糖果机实体类
 * UnicastRemoteObject是为远程rmi服务的
 */
public class CandyMachine extends UnicastRemoteObject implements CandyMachineRemote {

    State soldOutState;
    State onReadyState;
    State hasCoin;
    State soldState;
    State winnerState;

    private State state;
    private String location = "";
    private int count = 0;

    public CandyMachine(String location, int count) throws RemoteException {
        this.location = location;
        this.count = count;
        soldOutState = new SoldOutState(this);
        onReadyState = new OnReadyState(this);
        hasCoin = new HasCoinState(this);
        soldState = new SoldState(this);
        winnerState = new WinnerState(this);
        if (count > 0) {
            state = onReadyState;
        } else {
            state = soldOutState;
        }
    }

    public String getLocation() {
        return location;
    }

    public void setState(State state) {
        this.state = state;
    }

    public void insertCoin() {
        state.insertCoin();
    }

    public void returnCoin() {
        state.returnCoin();
    }

    public void turnCrank() {
        state.turnCrank();
        state.dispense();
    }

    void releaseCandy() {
        if (count > 0) {
            count = count - 1;
            System.out.println("a candy rolling out!");
        }
    }

    public int getCount() {
        return count;
    }

    public void printState() {
        state.printState();
    }

    public State getState() {
        return state;
    }
}
